import router, { constantRoute } from '@/router'

const state = () => ({
  permission_btn_list: [], // 按钮权限标识
  permission_routes: constantRoute // 左侧菜单
})

const getters = {

}

const mutations = {
  setBtnList (state, data) {
    state.permission_btn_list = data
  },
  setPermissionMenu (state, data) {
    state.permission_routes = [...constantRoute, ...data]
  }
}

const actions = {
  // 处理路由，将路由动态添加到路由映射表中
  async generateRoutes ({ commit }, data) {
    // 将后台返回的处理成前端需要的形式
    const asyncRoutes = formateRoutes(data)
    // 设置到vuex中
    commit('setPermissionMenu', asyncRoutes)

    router.addRoutes(asyncRoutes)
  }
}

// 路由懒加载
export const loadView = (view) => {
  if (view === 'layout') {
    return (resolve) => require(['@/layout'], resolve)
  } else {
    return (resolve) => require([`@/views/${view}`], resolve)
  }
}
function notHiddenMenusNumber (menus) {
  return menus.filter(menu => {
    return menu.hidden === false
  }).length
}
// 递归处理后台返回的路由菜单数据
function formateRoutes (menus, $pid = 0) {
  // 1. 存储数据
  const routes = []
  // 2. 遍历每个元素
  menus.forEach(item => {
    if (item.pid === $pid) {
      const p = {}
      p.path = item.path // 路径
      p.name = item.mark // 路由名称
      item.redirect && (p.redirect = item.redirect) // 重定向
      p.componentName = item.component
      p.component = loadView(item.component) // 组件
      p.meta = {}
      p.meta.title = item.title // 标题
      p.meta.icon = item.icon // 图标
      if (item.is_cache === 1) { // 是否缓存
        p.meta.noCache = true
      } else {
        p.meta.noCache = false
      }
      if (item.is_show === 0) { // 是否隐藏
        p.hidden = true
      } else {
        p.hidden = false
      }
      const children = formateRoutes(menus, item.id)
      const childNum = notHiddenMenusNumber(children)
      if (childNum) {
        p.children = children
        if (childNum >= 1) {
          p.alwaysShow = true
        }
      }
      routes.push(p)
    }
  })
  return routes
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
